<?php
declare (strict_types=1);

namespace app\common\model;
use think\model\relation\HasOne;

class BusinessDraw extends Base
{
    protected $name = 'business_draw';

    public function user(): HasOne
    {
        return $this->hasOne(User::class, 'id', 'uid')->field('id,code,nickname,mobile');
    }

    public function business(): HasOne
    {
        return $this->hasOne(Business::class, 'id', 'business_id')
            ->field('id,title,contacts,mobile,license,bank_name,bank_open,bank_account,bank_number,draw,drawing,drawed');
    }

    public function getStatusAttr($value): string
    {
        switch ($value) {
            case 1:
                return '待审核';
            case 2:
                return '已通过';
            case 3:
                return '已驳回';
            default:
                return '未知';
        }
    }

    /**
     * 提现申请
     * @param $param
     * @param $business
     * @param $system
     * @return array
     */
    public static function add($param, $business, $system): array
    {
        parent::startTrans();
        try {
            if (!$system['business_draw_open']) {
                return ['code' => -1, 'msg' => '暂时无法提现'];
            }

            $week = explode(',', $system['business_draw_week']);
            if (!in_array(date('w'), $week)) {
                return ['code' => -1, 'msg' => '每周' . $system['business_draw_week'] . '可提现'];
            }
            $times = explode(',', $system['business_draw_times']);
            $his = date('H:i:s');
            if ($his < $times[0] || $his > $times[1]) {
                return ['code' => -1, 'msg' => '提现时间为：' . $times[0] . ' ~ ' . $times[1]];
            }

            $count = parent::where('business_id', $business->id)->whereTime('create_time', 'today')->count();
            if ($count >= $system['business_draw_day']) {
                return ['code' => -1, 'msg' => '每日只可提现' . $system['draw_day'] . '次'];
            }

            if (!$param['money'] || $param['money'] <= 0) {
                return ['code' => -1, 'msg' => '提现金额错误'];
            }

            if ($param['money'] < $system['business_draw_min']) {
                return ['code' => -1, 'msg' => '最低提现金额：' . $system['business_draw_min']];
            }

            if ($system['business_draw_bs']) {
                if (isFloat($param['money']) || $param['money'] % $system['business_draw_bs'] != 0) {
                    return ['code' => -1, 'msg' => '提现倍数：' . $system['business_draw_bs']];
                }
            }

            if ($business->draw < $param['money']) {
                return ['code' => -1, 'msg' => '余额不足'];
            }
            if (md5($param['pay_password']) != $business['pay_password']) {
                return ['code' => -1, 'msg' => '支付密码错误'];
            }

            $cost = 0;
            if ($system['business_draw_cost'] && $system['business_draw_cost'] > 0) {
                $cost = round($param['money'] * $system['business_draw_cost'], 2);
            }

            $amount = round($param['money'] - $cost, 2);
            parent::create([
                'business_id' => $business->id,
                'uid'         => $business->uid,
                'money'       => $param['money'],
                'cost'        => $cost,
                'amount'      => $amount,
                'bank_name'   => $business->bank_name,
                'bank_open'   => $business->bank_open,
                'bank_account'=> $business->bank_account,
                'bank_number' => $business->bank_number
            ]);

            $business->draw -= $param['money'];
            $business->drawing += $amount;
            $business->save();

            parent::commit();
            return ['code' => 1, 'msg' => '申请已提交，请耐心等待审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /**
     * 提现审核
     * @param $param
     * @param $admin
     * @return array
     */
    public static function _save($param, $admin): array
    {
        parent::startTrans();
        try {
            if (!isset($param['status'])) return ['code' => -1, 'msg' => '请选择审核结果'];

            $info = parent::find($param['id']);
            if (empty($info)) return ['code' => -1, 'msg' => '提现记录不存在'];
            if ($info->getData('status') != 1) {
                return ['code' => -1, 'msg' => '此笔记录已审核，请勿重复审核！'];
            }

            $info->status = $param['status'];
            if ($param['status'] != 2) {
                $info->reject_msg = $param['reject_msg'];
            }
            $info->admin_id = $admin['id'];
            $info->admin_name = $admin['admin_name'];
            $info->save();

            $info->business->drawing -= $info['amount'];
            if($param['status'] == 2){
                $info->business->drawed += $info['amount'];
            }else{
                $info->business->draw += $info['money'];
            }

            $info->business->save();

            Logs::adds('商户提现', $admin['id'], $admin['admin_name']);
            parent::commit();
            return ['code' => 1, 'msg' => '已审核'];

        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }

    /*public static function batch($ids, $admin)
    {
        parent::startTrans();
        try {
            $infos = parent::where('status', 1)->whereIn('id', $ids)->select();
            if ($infos->isEmpty()) {
                return ['code' => -1, 'msg' => '未查询到待审核的数据，请检查！'];
            }
            $newIds = [];
            foreach ($infos as $v) {
                $newIds[] = $v->id;
            }
            parent::update(['status' => 2, 'admin_id' => $admin->id, 'admin_name' => $admin->admin_name], ['id' => $newIds]);
            parent::commit();
            $msg = '商户提现';
            Logs::adds($msg, $admin['id'], $admin['admin_name']);
            return ['code' => 1, 'msg' => '已批量审核'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }*/

}
